<template>
  <page-card title="用户管理"
             :sub-title="subTitle"
             :need-back="true">
    <a-row type="flex"
           justify="center">
      <a-col :span="7">
        <a-row type="flex">
          <a-col :span="24">
            <a-descriptions :title="changeUnitTitle" />
          </a-col>
          <div style="width:100%;overflow-x:auto">
            <a-tree :replace-fields="unitReplaceFields"
                    :showIcon="true"
                    :load-data="loadUnitTree"
                    :tree-data="unitTreeData"
                    @select="checkUnit">
              <a-icon slot="switcherIcon"
                      type="caret-down" />
              <a-icon slot="clazz"
                      type="appstore" />
              <a-icon slot="unit"
                      type="home" />
              <a-icon slot="dept"
                      type="bank" />
            </a-tree>
          </div>
        </a-row>
      </a-col>
      <a-col :span="1">
        <a-divider style="height:100%;margin-left:50%"
                   type="vertical" />
      </a-col>

      <a-col :span="15">
        <a-form-model :model="form"
                      :rules="rules"
                      :label-col="{ span: 6 }"
                      :wrapper-col="{ span: 12 }"
                      ref="form">
          <a-input type="hidden"
                   v-model="form.id" />
          <a-input type="hidden"
                   v-model="form.unitId" />
          <a-input type="hidden"
                   v-model="form.deptId" />
          <a-input type="hidden"
                   v-model="form.userVO.passwordSalt" />
          <a-col :span="24">
            <a-divider orientation="left">
              岗位信息
            </a-divider>
          </a-col>
          <a-form-model-item v-if="changeType!=0"
                             label="转岗前机构">
            {{ form.unitVO.fullName }}&nbsp;/&nbsp;{{ form.deptVO.fullName }}
          </a-form-model-item>
          <a-form-model-item v-if="changeType!=0"
                             label="当前选择机构">
            <span v-if="!checkUnitFlat">未选择</span>
            <span v-if="checkUnitFlat"><span v-text="selectUnit"></span>&nbsp;/&nbsp;<span
              v-text="selectDept"></span></span>
          </a-form-model-item>
          <a-form-model-item label="角色："
                             prop="roleIdList">
            <a-select v-model="form.roleIdList"
                      mode="multiple"
                      :default-value="form.roleIdList"
                      :filterOption="filterOption"
                      style="width: 100%"
                      placeholder="该用户角色">
              <a-select-option v-for="(role) in roleListData"
                               :key="role.id"
                               :value="role.id">
                {{ role.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item v-if="changeType==0"
                             label="主职标识："
                             prop="isMainJob">
            <a-radio-group name="radioGroup"
                           v-model="form.isMainJob">
              <a-radio value="1">主职</a-radio>
              <a-radio value="2">兼职</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="排序号："
                             prop="orderno">
            <a-input-number placeholder="正整数排序号"
                            v-model="form.orderno"
                            :min="0"
                            :max="1000000"
                            allow-clear />
          </a-form-model-item>
          <a-form-model-item label="岗位名称："
                             prop="jobName">
            <a-input placeholder="用户在该机构下的岗位名称，长度不超过50位"
                     :maxLength="50"
                     v-model="form.jobName"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="入职日期："
                             prop="joinTime">
            <a-date-picker v-model="form.joinTime"
                           type="date"
                           placeholder="入职日期"
                           style="width: 100%;" />
          </a-form-model-item>
          <a-form-model-item label="工号："
                             prop="workNo">
            <a-input placeholder="用户在该机构下的工号，长度不超过20位"
                     :maxLength="20"
                     v-model.trim="form.workNo"
                     allow-clear />
          </a-form-model-item>

          <a-form-model-item v-if="changeType==0"
                             label="单位邮箱："
                             prop="email">
            <a-input placeholder="单位邮箱，长度不超过100位"
                     :maxLength="100"
                     v-model.trim="form.email"
                     allow-clear />
          </a-form-model-item>

          <a-form-model-item v-if="changeType==0"
                             label="联系电话："
                             prop="tel">
            <a-input placeholder="联系电话，长度不超过20位"
                     :maxLength="20"
                     v-model.trim="form.tel"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label=" "
                             :colon="false">
            <div style="text-align:center">
              <a-button type="primary"
                        style="width: 80px;"
                        @click="save">保存</a-button>
            </div>
          </a-form-model-item>
        </a-form-model>
      </a-col>
    </a-row>

    <!-- <sync @cancel="cancel"
          :visible="syncVisible"
          :mediaType="mediaType"
          :syncType="syncType"
          :deptId="deptId"
          :mediaId="mediaId"></sync> -->
  </page-card>
</template>

<script>
import {
  syncUnitTree,
  getById,
  getRoleList,
  saveOrUpdateChange,
  changeInit
} from '../../api/user/index'
// import ArrayUtil from '@zh/common-utils/utils/array'

export default {
  data() {
    return {
      syncOff: null,
      syncVisible: false,
      mediaType: '2',
      deptId: '',
      syncType: '',
      mediaId: '',
      subTitle: '',
      changeUnitTitle: '',
      changeType: '',
      checkUnitFlat: false,
      selectDept: '',
      selectDeptId: null,
      selectUnit: '',
      selectUnitId: null,
      roleListData: [],
      unitTreeData: [],
      roleIdList: [],
      unitReplaceFields: { title: 'treeTitle' },
      form: {
        id: null,
        userVO: {
          id: null,
          type: '',
          fullname: '',
          img: null,
          account: '',
          password: '',
          tempPassWord: null,
          tel: '',
          status: '',
          sex: '',
          birthday: '',
          email: '',
          address: '',
          remark: '',
          zwddId: '',
          otherSysId: '',
          openId: '',
          idCard: '',
          unitIds: '',
          passwordSalt: ''
        },
        unitVO: {
          id: null,
          name: '',
          fullName: '',
          parentId: 0,
          actual: '1',
          code: '',
          orderNo: '',
          levelCode: '',
          state: '1',
          type: '1',
          openId: '1',
          otherSysId: '1',
          url: '',
          zwddId: '',
          contact: '',
          unitAddress: '',
          tel: '',
          unitnote: ''
        },
        deptVO: {
          id: null,
          name: '',
          fullName: '',
          parentId: 0,
          actual: '1',
          code: '',
          orderNo: '',
          levelCode: '',
          state: '1',
          type: '1',
          openId: '1',
          otherSysId: '1',
          url: '',
          zwddId: '',
          contact: '',
          unitAddress: '',
          tel: '',
          unitnote: ''
        }
      },
      rules: {
        email: [{ type: 'email', message: '邮箱格式不正确' }],
        orderno: [
          { required: true, message: '请输入排序号' },
          { pattern: /^[1-9]\d*$/, message: '排序号应该为正整数' }
        ],
        isMainJob: [{ required: true, message: '请选择用户主职标识' }],
        roleIdList: [{ required: true, message: '请选择用户角色' }]
      }
    }
  },
  // components: {
  //   ImageUploader, Sync
  // },
  created() {
    this.syncOff =
      !this.$store.getAppConfig('_syncOff') ||
      this.$store.getAppConfig('_syncOff') == 1
    this.loadRole()
  },
  mounted() {
    this.loadPage()
    this.loadUnitTree()
  },
  methods: {
    // 将输入的内容与显示的内容进行匹配
    filterOption (value, option) {
      return option.componentOptions.children[0].text.indexOf(value) >= 0
    },
    /**
     * 机构树，切换机构
     */
    checkUnit(selectedKeys, info) {
      if (info.node.dataRef.nodeType == '1') {
        this.message.info('请选择单位或部门')
        return
      }
      this.checkUnitFlat = true
      changeInit(info.node.dataRef.key, info.node.dataRef.nodeType).then(
        (res) => {
          this.form.orderno = res.orderNo
          this.selectDeptId = info.node.dataRef.key
          this.selectDept = info.node.dataRef.treeTitle
          if (info.node.dataRef.nodeType == '2') {
            this.selectUnit = info.node.dataRef.treeTitle
            this.selectUnitId = info.node.dataRef.key
          } else {
            this.selectUnit = res.selectUnitVO.name
            this.selectUnitId = res.selectUnitVO.id
          }
        }
      )
    },
    /**
     * 加载机构树
     */
    loadUnitTree(treeNode) {
      const topId = !treeNode ? 0 : treeNode.dataRef.key
      return new Promise((resolve) => {
        syncUnitTree(topId).then((res) => {
          if (treeNode) {
            treeNode.dataRef.children = res
            this.unitTreeData = [...this.unitTreeData]
            resolve()
          } else {
            this.unitTreeData = res
          }
        })
      })
    },
    /**
     * 加载角色
     */
    loadRole() {
      getRoleList().then((res) => {
        this.roleListData = res
      })
    },
    /**
     * 根据id参数 判断新增还是修改
     */
    loadPage() {
      this.loadRole()
      const id = this.$route.query.id
      const type = this.$route.query.type
      this.changeType = type
      this.subTitle = type != 0 ? '转岗' : '兼职'
      this.changeUnitTitle = type != 0 ? '转岗机构' : '兼职机构'
      // 初始化页面数据
      getById(id).then((res) => {
        this.form = res
        const newRoleIdList = []
        const roleDataIdList = this.roleListData.map((val) => {
          return val.id
        })
        if (this.form.roleIdList && this.form.roleIdList.length > 0) {
          for (let i = 0; i < this.form.roleIdList.length; i++) {
            const roleId = this.form.roleIdList[i]
            if (roleDataIdList.indexOf(roleId) == -1) {
              this.roleIdList.push(roleId)
            } else {
              newRoleIdList.push(roleId)
            }
          }
        }
        this.form.roleIdList = newRoleIdList
        if (type == 0) {
          this.form.id = null
          this.form.joinTime = null
          this.form.workNo = ''
          this.form.orderno = null
          this.form.email = ''
          this.form.tel = ''
          this.form.isMainJob = ''
        }
      })
    },

    /**
     * 保存
     */
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.selectUnitId || !this.selectDeptId) {
            this.message.warn(
              '未选择' + (this.changeType == 1 ? '转岗机构' : '兼职机构')
            )
            return
          }
          this.form.unitId = this.selectUnitId
          this.form.deptId = this.selectDeptId
          const userForm = this.form

          userForm.roleIdList.concat(this.roleIdList)
          saveOrUpdateChange(this.changeType, this.form).then((res) => {
            // this.message.info(
            //   this.changeType == 1 ? '转岗成功' : '新增兼职成功'
            // )
            this.$router.back()
          })
        }
      })
    },
    cancel() {
      this.syncVisible = false
      this.$router.back()
    },
    sync() {
      this.syncVisible = true
      this.mediaId = this.form.userId
      this.deptId = this.form.deptId
      this.syncType = '2'
    }
  }
}
</script>

<style lang="less" scoped>
.x-row {
  border: 0px solid #d9d9d9;
}
</style>
